//
// Created by Tony on 2024/3/2.
//

#include "ByteCodeReader.h"
#include <stdexcept>

namespace Runtime {

ByteCodeReader::ByteCodeReader(const shared_ptr<RtCode::Code>& code, uint32_t pc)
    : mCode(code), mPC(pc) {}

ByteCodeReader::ByteCodeReader() : ByteCodeReader(nullptr, 0) {}

void ByteCodeReader::reset(const shared_ptr<RtCode::Code>& code, uint32_t pc) {
    this->mCode = code;
    this->mPC = pc;
}

OpCode ByteCodeReader::readOpCode() {
    if (mPC >= mCode->size()) {
        throw std::runtime_error("read opcode out of range.");
    }
    return static_cast<OpCode>(mCode->readUint8(mPC++));
}

uint16_t ByteCodeReader::readUint16() {
    auto ret = mCode->readUint16(mPC);
    mPC += 2;
    return ret;
}

int16_t ByteCodeReader::readInt16() {
    auto ret = mCode->readInt16(mPC);
    mPC += 2;
    return ret;
}

uint32_t ByteCodeReader::getNextPC() const { return mPC; }

} // namespace Runtime